package cn.tannn.tregistry.core.json;

import cn.tannn.tregistry.core.model.InstanceMeta;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.reader.ObjectReader;
import org.springframework.util.LinkedMultiValueMap;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;


/**
 * 自定义反序列化
 * @see https://github.com/alibaba/fastjson2/issues/1249
 */
public class LinkedMultiValueMapDeserializer implements ObjectReader<LinkedMultiValueMap<String, InstanceMeta>> {

    @Override
    public LinkedMultiValueMap<String, InstanceMeta> readObject(JSONReader jsonReader
            , Type fieldType
            , Object fieldName
            , long features) {
        LinkedMultiValueMap<String, InstanceMeta> linkedMultiValueMap = new LinkedMultiValueMap<>();

        Map<String, Object> jsonObject = jsonReader.readObject();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if(value instanceof JSONObject){
                InstanceMeta instanceMeta = ((JSONObject) value).to(InstanceMeta.class);
                linkedMultiValueMap.add(key, instanceMeta);
            }else if(value instanceof JSONArray){
                List<InstanceMeta> instanceMetas = JSONArray.parseArray(value.toString(), InstanceMeta.class);
                linkedMultiValueMap.addAll(key, instanceMetas);
            }
        }
        return linkedMultiValueMap;
    }
}
